package com.example.controller;

import com.example.conf.FastDFSConf;
import com.example.utils.FastDFSClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class UploadController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FastDFSConf fastDFSConf;

    /**
     * 文件上传
     * <p>
     * 从 MultipartFile中 读取文件流信息，然后使用 FastDFSClient 将文件上传到 FastDFS 中
     */
    @PostMapping("/upload")
    public String singleFileUpload(@RequestParam("file") MultipartFile multipartFile) {
        if (multipartFile.isEmpty()) {
            return "请选择要上传到文件";
        }
        try {
            String fileName = multipartFile.getOriginalFilename();
            String ext = fileName.substring(fileName.lastIndexOf(".") + 1);

            // 文件流
            byte[] file_buff = null;
            InputStream inputStream = multipartFile.getInputStream();
            if (inputStream != null) {
                int len1 = inputStream.available();
                file_buff = new byte[len1];
                inputStream.read(file_buff);
            }
            inputStream.close();

            // 上传
            Map<String, String> metaData = new HashMap<>();
            metaData.put("author", "刘仁奎");
            metaData.put("webSite", "程序喵");
            metaData.put("home", "http://www.ibloger.net");
            String[] fileAbsolutePath = FastDFSClientUtil.upload(fileName, file_buff, ext, metaData);
            if (fileAbsolutePath == null) {
                logger.error("上传文件异常，请重新上传!");
            }

            // 创建 token
            String token = FastDFSClientUtil.getToken(fileAbsolutePath[1], fastDFSConf.getHttp_secret_key());
            String path = fastDFSConf.getUrl() + fileAbsolutePath[0] + "/" + fileAbsolutePath[1] + "?" + token;
            logger.info("path = {}", path);
            return path;
        } catch (Exception e) {
            logger.error("上传失败", e);
        }
        return null;
    }

}
